package com.pinyougou.shop.controller;


import com.pinyougou.pojo.Seller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/seller")
public class LoginController
{
    @PostMapping("/login")
    public String login(Seller seller)
    {
        try
        {
            //1.获取subject
            Subject subject = SecurityUtils.getSubject();
            //2. 构造用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken(seller.getSellerId(), seller.getPassword());
            //3. 借助subject 完成用户登录
            subject.login(token);
            //4. 通过shiro获取用户对象，保存在session中
            //5. 登陆成功跳转页面
            if(subject.isAuthenticated())
            {
                //使用转发会导致乱码问题，使用重定向不会乱码？？？
                /*return "forward:/admin/index.html";*/
                return "redirect:/admin/index.html";
            }
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
        }
            //6. 登录失败跳转页面
            return "redirect:/shoplogin.html";
    }

    @GetMapping("/findLoginSeller")
    @ResponseBody
    public String findLoginSeller()
    {
        return SecurityUtils.getSubject().getPrincipal().toString();

    }
}